package com.ysm.smfu.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ysm.smfu.R;
import com.ysm.smfu.bean.PayResult;
import com.ysm.smfu.contans.SpKey;
import com.ysm.smfu.protocal.BaseProtocal;
import com.ysm.smfu.protocal.MyStringCallBack;
import com.ysm.smfu.utils.JsonUtil;
import com.ysm.smfu.utils.Md5Utils;
import com.ysm.smfu.utils.StoreInfo;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.ToastUtils;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.view.PayPwdEditText;
import com.ysm.smfu.welcome.SharedConfig;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/10/27.
 */
public class ZhiFuActivity extends BaseActivity {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title_body)
    TextView titleBody;
    @BindView(R.id.zhifu_clear)
    TextView zhifuClear;
    @BindView(R.id.zhifu_text)
    TextView zhifuText;
    @BindView(R.id.fragment_zhifu_psd)
    PayPwdEditText fragmentZhifuPsd;
    @BindView(R.id.mainActivity_topbar_img)
    ImageView mainActivity_topbar_img;
    @BindView(R.id.alert_psd)
    TextView alertPsd;
    @BindView(R.id.alert_forget)
    TextView alertForget;
    private ProgressDialog progressDialog;
    private AlertDialog dialog;
    private MyReceiver myreceiver;
    private SharedPreferences currShared;

    @Override
    protected void initViews() {
        super.initViews();
        setContentView(R.layout.activity_zhifu);
        ButterKnife.bind(this);
        getConfig();
        registerForFinish();
    }

    private void getConfig() {
        titleBody.setText("支付密码");
        mainActivity_topbar_img.setVisibility(View.GONE);
        fragmentZhifuPsd.initStyle(R.drawable.edit_num_bg, 6, 0.5f, R.color.color999999, R.color.color999999, 20);
        zhifuText.setText("请输入支付密码");
        final String name = new SharedConfig(UIUtils.getContext()).getCommoneSp().getString(SpKey.NAME, "");
        currShared = new SharedConfig(UIUtils.getContext(), name).getPrivateSp();
        final String level = currShared.getString(SpKey.LEVEL, "");

        alertForget.setVisibility(View.VISIBLE);
        Intent intent = getIntent();
        final String pay_businessid = intent.getStringExtra(SpKey.Pay_BUSSINESSID);
        final String jifen = intent.getStringExtra(SpKey.JIFEN);
        final String money = intent.getStringExtra(SpKey.MONEY);

        // 输入完成时调用
        fragmentZhifuPsd.setOnTextFinishListener(new PayPwdEditText.OnTextFinishListener() {
            @Override
            public void onFinish(String str) {
                showDialg();
                String psd = Md5Utils.encode(str);
                toPayMoney(pay_businessid, jifen, money, psd, level);
            }
        });
    }

    /**
     * 余额支付
     *
     * @param psd
     * @param businessId
     */
    private void toPayMoney(String businessId, String jifen, String money, String psd, String level) {
        BaseProtocal.builder(true).toPayMoney(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("余额支付", response);
                cancleDialog();
                String state = JsonUtil.getState(response);
                if (!TextUtils.equals(state, "1")) {
                    fragmentZhifuPsd.clearText();
                    showErrDialog(JsonUtil.getMessage(response));
                    return;
                }
                //余额支付成功，将相关支付数据清空
                StoreInfo.getInstance().clearPayInfo(currShared);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONObject result = jsonObject.optJSONObject("result");
                    String obj = result.optString("obj");
                    PayResult payResult = new Gson().fromJson(obj, PayResult.class);
//                 支付成功后，跳转支付成功界面
                    Intent intent = new Intent(ZhiFuActivity.this, XiangQingActivity.class);
                    intent.putExtra("xiangqing", 1);
                    intent.putExtra(SpKey.PAYRESULT, payResult);
                    startActivity(intent);
                } catch (JSONException e) {

                }
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.showToast("支付失败：" + e.getMessage());
            }
        }, businessId, jifen, psd, money, level);
    }


    @OnClick({R.id.zhifu_clear, R.id.back, R.id.alert_forget})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.zhifu_clear:
                fragmentZhifuPsd.clearText();
                break;
            case R.id.back:
                finish();
                break;
            case R.id.alert_forget:
                //  修改支付密码
                Intent intent = new Intent(this, Registe_checkActivity.class);
                intent.putExtra(SpKey.INTENT, "zhifupsd");
                intent.putExtra(SpKey.INTENT2, "zhifupsd2");
                startActivity(intent);
                finish();
                // 设置Activity的切换效果
                overridePendingTransition(R.anim.in_from_right,
                        R.anim.out_to_left);
                break;
        }
    }

    public void showErrDialog(final String msg) {
        dialog = new AlertDialog.Builder(this)
                .setMessage(msg)
                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        UIUtils.startActivity(MainActivity.class);
                        if (!TextUtils.equals(msg, "支付密码不正确"))
                            finish();
                    }
                })
                .create();
        dialog.show();
    }

    /**
     * 显示进度对话框
     */
    private void showDialg() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在支付...");
        if (!progressDialog.isShowing())
            progressDialog.show();
    }

    private void cancleDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.setMessage("支付成功...");
            progressDialog.dismiss();
        }
    }

    /**
     * 接收广播，关闭自己
     */
    private void registerForFinish() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("finfisPrepay");
        myreceiver = new MyReceiver();
        registerReceiver(myreceiver, intentFilter);
    }

    class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myreceiver);
    }
}
